const { MongoClient } = require("mongodb");

const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);

async function getCollection(collectionName) {
    await client.connect();
    const db = client.db("Dormitory");
    return db.collection(collectionName);
}

function executeQuery(collectionName, onCollectionGot) {
    // console.log(client);
    function callback() {
        client.close();
    }
    getCollection(collectionName).then((collection) => {
        onCollectionGot(collection, callback);
    });
}

function baseQuery(collectionName, promiseTask, onRetGot, onErrGot, callback) {
    executeQuery(collectionName, (collection, callback) => {
        promiseTask(collection)
            .then((result) => {
                onRetGot(result);
                client.close();
            })
            .catch((err) => {
                onErrGot(err);
                client.close();
            });
    });
}

module.exports = {
    executeQuery,
    baseQuery,
};
